# -*-coding: UTF-8 -*-
# @File : AllureLogStepHandler .py
# author: huangchen
# Time：2024/1/10
import io
import allure
import allure_commons
from _pytest.logging import LogCaptureHandler


class AllureLogStepHandler:
    def __init__(
            self, capture_handler: LogCaptureHandler = None
    ):
        self._capture_handler = capture_handler
        self._io_stack = []

    @allure_commons.hookimpl
    def start_step(self, uuid, title, params):
        if self._capture_handler:
            stream = self._capture_handler.setStream(io.StringIO())
            self._io_stack.append(stream)

    @allure_commons.hookimpl
    def stop_step(self, uuid, exc_type, exc_val, exc_tb):
        if self._capture_handler:
            previous_stream = self._io_stack.pop()
            stream = self._capture_handler.setStream(previous_stream)
            step_logs = stream.getvalue().strip()
            if step_logs:  # 有日志记录时，在测试步骤中单独记录log
                allure.attach(
                    step_logs,
                    name="log",
                    attachment_type=allure.attachment_type.TEXT,
                )
